package com.lnj.community.advice;

import com.lnj.community.utiles.CommunityUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.io.IOException;

//@ControllerAdvice是一个注解,用于处理异常的类
//控制器增强器,用于处理异常的类
@ControllerAdvice(annotations = {Controller.class})
public class ExceptionAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
    //处理异常的方法    异常类型  异常对象
    //@ExceptionHandler是一个注解,用于处理异常的方法
    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
       logger.error("服务器发生异常:"+e.getMessage());
       //打印异常栈信息
       for (StackTraceElement element : e.getStackTrace()) {
           logger.error(element.toString());
       }
       //判断请求的类型
       if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
           //异步请求
           response.setContentType("application/plain;charset=utf-8");
           try {
               response.getWriter().write(CommunityUtil.getJSONString(1,"服务器异常"));
           }catch (Exception ex) {
               ex.printStackTrace();
           }
       }else {
           // 同步请求，检查响应是否已经提交
           if (!response.isCommitted()) {
               try {
                   response.sendRedirect(request.getContextPath() + "/error");
               } catch (IOException ex) {
                   ex.printStackTrace();
               }
           }
       }
    }
}
